const { Paragraph, TextRun, ImageRun } = require("docx");
const fs = require('fs');
const path = require('path');
const { getAlignment, getIndentValue, getPrefixSymbol, mapFontSizeToHalfPoints } = require("../common/utils");

// cm 转 EMU（docx 内部单位）
const CM_TO_EMU = 360000;
const cmToEMU = (cm) => Math.max(0, (cm || 0) * CM_TO_EMU);

// 生成图片字段
function generateImageField(field, baseIndent = 0) {
  const v = field?.value || {};
  const img = v.image || {};

  const elements = [];

  // 1) 前置文本（可选）
  if (v.captionBefore || v.fieldName) {
    const children = [];
    if (v.prefixSymbol) {
      children.push(new TextRun({ text: getPrefixSymbol(v.prefixSymbol), font: 'SimSun', size: mapFontSizeToHalfPoints(v.fontSize || '五号') }));
    }
    if (v.fieldName) {
      children.push(new TextRun({ text: ` ${v.fieldName} `, font: 'SimSun', size: mapFontSizeToHalfPoints(v.fontSize || '五号'), bold: !!v.isBold }));
    }
    if (v.captionBefore) {
      children.push(new TextRun({ text: v.captionBefore, font: 'SimSun', size: mapFontSizeToHalfPoints(v.fontSize || '五号'), bold: !!v.isBold }));
    }
    elements.push(new Paragraph({
      indent: { left: getIndentValue(v.alignment, baseIndent) },
      alignment: getAlignment(v.alignment),
      spacing: { before: 100, after: 100 },
      children
    }));
  }

  // 2) 图片主体
  if (img?.url) {
    try {
      // 将 /uploads/... URL 转为本地文件路径
      let localPath = img.url;
      if (localPath.startsWith('/')) localPath = localPath.slice(1);
      const absPath = path.join(__dirname, '..', '..', localPath);
      const data = fs.readFileSync(absPath);

      // 尺寸转换 px（docx ImageRun 以像素为单位）
      const cmToPx = (cm) => Math.round((cm || 0) / 2.54 * 96);
      const widthPx = cmToPx(img.widthCm || 8);
      const heightPx = cmToPx(img.heightCm || img.widthCm || 8);

      const run = new ImageRun({
        data,
        transformation: {
          width: widthPx,
          height: heightPx
        }
      });

      elements.push(new Paragraph({
        indent: { left: getIndentValue(v.alignment, baseIndent) },
        alignment: getAlignment(v.alignment),
        spacing: { before: 50, after: 50 },
        children: [run]
      }));
    } catch (e) {
      // 读取失败则输出占位文本
      elements.push(new Paragraph({
        indent: { left: getIndentValue(v.alignment, baseIndent) },
        alignment: getAlignment(v.alignment),
        children: [
          new TextRun({ text: v.image?.alt || '[图片不可用]', font: 'SimSun', size: mapFontSizeToHalfPoints(v.fontSize || '五号'), bold: true })
        ]
      }));
    }
  }

  // 3) 后置文字（可选）
  if (v.captionAfter) {
    elements.push(new Paragraph({
      indent: { left: getIndentValue(v.alignment, baseIndent) },
      alignment: getAlignment(v.alignment),
      spacing: { before: 100, after: 50 },
      children: [
        new TextRun({ text: v.captionAfter, font: 'SimSun', size: mapFontSizeToHalfPoints(v.fontSize || '五号'), bold: !!v.isBold })
      ]
    }));
  }

  return elements;
}

module.exports = {
  generateImageField
};


